package com.isoft.illustrationsdraw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.isoft.illustrationsdraw.entity.Message;
import com.isoft.illustrationsdraw.mapper.MessageMapper;
import com.isoft.illustrationsdraw.service.MessageService;

import java.util.List;

import org.springframework.stereotype.Service;

@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    private final MessageMapper messageMapper;

    public MessageServiceImpl(MessageMapper messageMapper) {
        this.messageMapper = messageMapper;
    }


    @Override
    public List<Message> getHistoryMessage(Long senderId, Long receiverId, Integer page) {
        // 每页的记录数量，假设为 20 条
        int pageSize = 20;

        // 创建 QueryWrapper
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .nested(wrapper -> wrapper.eq("sender_id", senderId).eq("receiver_id", receiverId))
                .or(wrapper -> wrapper.eq("sender_id", receiverId).eq("receiver_id", senderId))
                .orderByDesc("timestamp"); // 按时间倒序排序

        // 使用分页查询
        Page<Message> pagination = new Page<>(page, pageSize);
        Page<Message> resultPage = messageMapper.selectPage(pagination, queryWrapper);

        return resultPage.getRecords(); // 返回分页结果中的记录
    }
}
